package com.system.security.handler;

import com.component.domain.MUserToken;
import com.component.service.MUserTokenService;
import com.system.config.JWTConfig;
import com.system.security.domain.SelfUserEntity;
import com.system.util.JWTTokenUtil;
import com.system.util.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Xiongx
 * @version 1.0
 * @date 2021/6/11 15:10
 * @since JDK 1.8
 */
@Slf4j
@Component
public class UserLoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private MUserTokenService mUserTokenService;

    /**
     * 登录成功返回结果
     * @Author Sans
     * @CreateTime 2019/10/3 9:27
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication){
        // 组装JWT
        SelfUserEntity selfUserEntity =  (SelfUserEntity) authentication.getPrincipal();
        String token = JWTTokenUtil.createAccessToken(selfUserEntity);
        token = JWTConfig.tokenPrefix + token;
        // 封装返回参数
        Map<String,Object> resultData = new HashMap<>();
        resultData.put("code","200");
        resultData.put("msg", "登录成功");
        resultData.put("token",token);

        MUserToken mUserToken=new MUserToken();
        mUserToken.setUserid(selfUserEntity.getUserId().toString());
        mUserToken.setUsername(selfUserEntity.getUsername());
        mUserToken.setLogindate(new Date());
        mUserToken.setIsDisabled(true);
        mUserToken.setToken(token);
        mUserTokenService.save(mUserToken);

        Cookie cookie = new Cookie(JWTConfig.tokenHeader, token);

        // 设置Cookie的其他属性（可选）
        cookie.setMaxAge(3600); // 设置Cookie的生命周期，单位为秒
        cookie.setPath("/"); // 设置Cookie的路径
        // 其他属性，如：cookie.setDomain("domain.com");
        // 将Cookie添加到响应中
        response.addCookie(cookie);
        ResultUtil.responseJson(response,resultData);
    }
}
